import os
from glob import glob

import cv2
import numpy as np

from libs.font_utils import check_font_chars, load_font
from libs.utils import load_chars


def main():
    base_dir = "/home/chenlei/all/Desktop/data_ZhuHai/"
    chars_file = "../../dict/char_9068/dict_scan.txt"
    chars = load_chars(chars_file)
    chars = ''.join(chars)
    with open(os.path.join(base_dir, "font/font_list/font_list.txt"), 'w', encoding="utf-8") as f:
        for font_path in glob(base_dir + "font/fonts_0129/zh/*"):
            ttf = load_font(font_path)
            unsupported_chars, supported_chars = check_font_chars(ttf, chars)
            print('Save font(%s) supported chars(%d) to cache, support rate(%f)' % (
                font_path, len(supported_chars), len(supported_chars) / (len(supported_chars) + len(unsupported_chars))))
            print("unsupport chars: ", unsupported_chars)
            f.write(font_path + "\n")


def get_image_info():
    hs = []
    ws = []
    for i, img_path in enumerate(glob("/home/chenlei/data/datasets/ZhuHai/0323_ocr_testset/IMG_dst/*.jpg")):
        print(f"{i}")
        img = cv2.imread(img_path)
        hs.append(img.shape[0])
        ws.append(img.shape[1])
    print(f"average h: {np.mean(hs)}")
    print(f"average w: {np.mean(ws)}")


def get_label_info():
    total = {}
    with open("/home/chenlei/data/datasets/ZhuHai/0323_ocr_testset/0323.txt", 'r', encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            line = line[15:].strip()
            length = len(line)
            if length in total:
                total[length] += 1
            else:
                total[length] = 1
        total = dict(sorted(total.items(), key=lambda kv: kv[0]))
        weights = []
        for k, v in total.items():
            weight = v * 1000 // len(lines)
            weights.append(weight)
            print("k={}, v={}, rate={}, weight={}".format(k, v, v / len(lines), weight))
        print(weights)


def bgr_to_gray():
    base_dir = "/home/chenlei/all/Desktop/data_ZhuHai/datasets/tr_v2/tr1_color0-50"
    for img_path in glob(base_dir + "/default/*.jpg"):
        img = cv2.imread(img_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(os.path.join(base_dir, "default_gray", os.path.basename(img_path)), img)


def test_bgr():
    img_path = "/home/chenlei/all/Desktop/data_ZhuHai/datasets/tr_v2/tr1_color0-50/default/00000008.jpg"
    img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
    img_ = cv2.imread(img_path)
    img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_1 = cv2.cvtColor(img_, cv2.COLOR_BGR2RGB)
    print(img[0][0])
    print(img_[0][0])


if __name__ == '__main__':
    # main()
    # get_image_info()
    # get_label_info()
    # bgr_to_gray()
    test_bgr()
